<template>
  <!-- 申请批次详情 -->
  <div class="detail">
    <Header :text="text"/>
    <div class="detail-content">
       <el-collapse v-model="activeNames">
          <el-collapse-item :title="$t('cArroval.message')" name="1">
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cArroval.applyBatch')}}: </span>{{transportObj.applyBatch}}</el-col>
              <el-col :span="13"><span class="weight">{{$t('cTransportSearch.transportState')}}: </span>{{$t(getState(transportObj.state))}}</el-col>
            </el-row>
            <el-row>
              <el-col :span="11" class="flexText">
                <span class="weight">{{$t('cArroval.people')}}: </span>
                <span>{{transportObj.applicant}}</span>
              </el-col>
              <el-col :span="13"><span class="weight">{{$t('cArroval.applyDate')}}: </span><span v-if="transportObj.applicationTime">{{transportObj.applicationTime.substring(0,16)}}</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cArroval.firtstApprover')}}: </span>{{transportObj.approver}}</el-col>
              <el-col :span="13"><span class="weight">{{$t('cArroval.approvalTime')}}: </span><span v-if="transportObj.approvalTime">{{transportObj.approvalTime.substring(0,16)}}</span></el-col>
            </el-row>
            <el-row>
              <span class="weight">{{$t('cArroval.applicationReason')}}: </span>{{transportObj.applicationReason}}
            </el-row>
            <el-row>
              <el-card class="box-card">
                <div slot="header">
                  <span>{{$t('cArroval.remark')}}</span>
                </div>
                <div v-if="transportObj.innerRemarksInfoEntityList.length !== 0">
                  <div v-for="item in transportObj.innerRemarksInfoEntityList" :key="item.id">
                    <div>
                      <span>{{transportObj.applicant}} </span> <span> {{transportObj.applicationTime}}</span>
                    </div>
                    <div style="color: red" v-if="item.newState === 3 && item.oldState=== 1">状态: 待审批 -> 已驳回</div>
                    <div>{{item.remarks}}</div>
                  </div>
                </div>
                <div v-else>无</div>
              </el-card>
            </el-row>
          </el-collapse-item>
          <el-collapse-item v-if="transportObj.transportType === '专车运输'" title="用车信息" name="2">
            <el-row>
              <el-col class="flexText">
                <span class="weight">{{$t('cTransportSearch.deliveryUnitCar')}}: </span>
                <span>{{transportObj.applicationUnit}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cTransportSearch.targetStation')}}:</span> {{transportObj.targetStation}}</el-col>
              <el-col :span="13"><span class="weight">{{$t('cTransportSearch.startStation')}}: </span>{{transportObj.startStation}}</el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cTransportSearch.deliveryUnit')}}: </span>{{transportObj.deliveryUnit}}</el-col>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cTransportSearch.deliveryPeople')}}: </span>{{transportObj.deliveryPeople}}</el-col>
            </el-row>
            <el-row>
              <span class="weight">{{$t('cTransportSearch.deliveryPhone')}}:</span> <span>{{transportObj.deliveryPhone}}<span v-if="transportObj.senderPhone"> | {{transportObj.senderPhone}}</span></span>
            </el-row>
            <el-row>
              <el-col class="flexText">
                <span class="weight">{{$t('cTransportSearch.receiveUnit')}}: </span>
                <span>{{transportObj.receiveUnit}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cTransportSearch.receivePeople')}}: </span>{{transportObj.receivePeople}}</el-col>
            </el-row>
            <el-row>
              <span class="weight"><span class="weight">{{$t('cTransportSearch.receivePhone')}}: </span></span><span>{{transportObj.receivePhone}} <span v-if="transportObj.sparePhone !== ''">| {{transportObj.sparePhone}}</span></span>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cTransportSearch.carrier')}}: </span>{{transportObj.carrier}}</el-col>
              <el-col :span="11"><span class="weight">{{$t('cArroval.estimatedFreight')}}: </span>{{transportObj.estimatedFreight}}</el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cTransportSearch.carType')}}: </span><span v-if="transportObj.innerCarInfoEntity">{{transportObj.innerCarInfoEntity.carType}}</span></el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cTransportSearch.appointment')}}:</span>
                <span v-if="transportObj.innerTransportEntity && transportObj.innerTransportEntity.estimateSendcarsDate">
                  {{transportObj.innerTransportEntity.estimateSendcarsDate.substring(0,11)}}{{timer[transportObj.innerTransportEntity.estimateSendcarsEndDate-1]}}
                </span>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item v-else :title="$t('cArroval.thingInfo')" name="2">
            <el-row>
              <el-col><span class="weight">{{$t('cTransportSearch.sending')}}: </span>{{transportObj.deliveryUnit}}</el-col>
            </el-row>
            <el-row>
              <el-col class="flexText">
                <span class="weight">{{$t('cArroval.adress')}}: </span>
                <span>{{transportObj.deliveryAddress}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cArroval.deliveryPeople')}}: </span>{{transportObj.deliveryPeople}}</el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cArroval.deliveryPhone')}}: </span>{{transportObj.deliveryPhone}} <span v-if="transportObj.senderPhone">| {{transportObj.senderPhone}}</span> </el-col>
            </el-row>
            <el-row>
              <el-col class="flexText">
                <span class="weight">{{$t('cArroval.receiveUnit')}}: </span>
                <span>{{transportObj.receiveUnit}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col class="flexText">
                <span class="weight">{{$t('cArroval.receiveAddress')}}: </span>
                <span>{{transportObj.receiveAddress}}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col><span class="weight">{{$t('cArroval.receivePeople')}}: </span>{{transportObj.receivePeople}}</el-col>
            </el-row>
            <el-row>
              <el-col>
                <div class="phone">
                  <div class="weight">{{$t('cArroval.receivePhone')}}: </div>
                  <div style="flex: 1">{{transportObj.receivePhone}} <span v-if="transportObj.sparePhone !== ''">| {{transportObj.sparePhone}}</span></div>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cTransportSearch.carrier')}}: </span>{{transportObj.carrier}}</el-col>
              <el-col :span="13"><span class="weight">{{$t('cTransportSearch.carType')}}: </span><span v-if="transportObj.innerCarInfoEntity">{{transportObj.innerCarInfoEntity.carType}}</span></el-col>
            </el-row>
            <el-row>
              <el-col :span="11"><span class="weight">{{$t('cArroval.estimatedFreight')}}: </span>{{transportObj.estimatedFreight}}</el-col>
              <el-col :span="13"><span class="weight">{{$t('cArroval.tihuoTime')}}:</span>
                <span v-if="transportObj.innerTransportEntity && transportObj.innerTransportEntity.estimateSendcarsDate">{{transportObj.innerTransportEntity.estimateSendcarsDate.substring(0,11)}}</span>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="货物列表" name="4">
            <div class="box" v-if="transportObj.innerGoodsInfoEntityList && transportObj.innerGoodsInfoEntityList.length !== 0">
              <div class="box-content" v-for="item in transportObj.innerGoodsInfoEntityList" :key="item.id">
                <div class="box-content-text">
                  <span>{{$t('cArroval.aog')}}: <span style="color:red" v-if="item.aog === 1">AOG</span><span v-else>{{$t('cArroval.noAog')}}</span></span>
                  <span>{{$t('cTransportSearch.addTime')}}: {{item.addTime ? item.addTime.substring(0,11):''}}</span>
                </div>
                <div class="box-content-text">
                  <span class="contraName">{{$t('cTransportSearch.itemName')}}: {{item.itemName}}</span>
                  <span>{{$t('cTransportSearch.danger')}}: <span v-if="item.danger === 1">{{$t('m.yes')}}</span><span v-else>{{$t('m.no')}}</span></span>
                </div>
                <div class="box-content-text">
                  <span>{{$t('cTransportSearch.partNum')}}: {{item.partNum}}</span>
                  <span>{{$t('cTransportSearch.serialNum')}}: {{item.serialNum}}</span>
                </div>
                <div class="box-content-text">
                  <span>{{$t('cTransportSearch.number')}}: {{item.number}}</span>
                  <span>{{$t('cTransportSearch.size')}}: <span v-if="item.itemLength">{{item.itemLength}} * {{item.itemWidth}} * {{item.itemHeight}}{{item.measurement}}</span></span>
                </div>
                <div class="box-content-text">
                  <span>{{$t('cTransportSearch.itemWeight')}}: {{item.itemWeight}}{{item.weightUofm}}</span>
                  <span>{{$t('cTransportSearch.packingType')}}: {{$t(item.packingType)}}</span>
                </div>
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item :title="$t('cTransportSearch.files')" name="3">
            <div v-for="item in plainOptions" :key="item.value">
              <div v-if="arr.length && arr.indexOf(item.value) > -1" class="text">
                <a href="#" style="color: #409eff">{{item.name}}</a>
              </div>
            </div>
          </el-collapse-item>
       </el-collapse>
    </div>
    <div class="bottom" v-if="show">
      <el-button type="danger" @click="handleCancel" v-if="transportObj.state === 1 || transportObj.state === 2">{{$t('btn.refush')}}</el-button>
      <el-button type="warning" v-if="isShow" @click="handleChange(transportObj.id)">转换类型</el-button>
      <el-button type="primary" @click="handleOk" v-if="transportObj.state === 1 || transportObj.state === 2">{{$t('btn.agree')}}</el-button>
      <el-button type="danger" v-if="transportObj.state === 3" @click="handleDelete">{{$t('btn.cancel')}}</el-button>
      <el-button type="primary" v-if="transportObj.state === 3" @click="handleisDistribution">{{$t('btn.distribution')}}</el-button>
    </div>
    <component
        :is="modalName"
        :applyObj="transportObj"
        :isDistribution="isDistribution"
        :isManager="isManager"
        @handleClose="handleClose"/>
    <van-image-preview
        v-model="isShowPreview"
        :images="previewImages"
        :startPosition="index"
        :loop="true"
    />
  </div>
</template>

<script>
import Ok from '@/views/transport/carTransport/components/Ok'
import No from '@/views/transport/carTransport/components/No'
import Header from "@/components/common/Header"
import { approvalState,timer, fileName } from "@/assets/js/common"
import { $approval } from '@/api/approval'
import { Notify } from 'vant'
import { ImagePreview } from 'vant'
export default {
  data() {
    return {
      text: '',
      activeNames: ['1','2','3','4'],
      show: false,
      modalName: '',
      transportObj: {},
      isDistribution: 0,
      previewImages: [],
      isShowPreview: false,
      imgOk: [], // 已加载的图片
      index: 0,
      timer,
      isShow: false,
      url: '',
      isManager: false,
      plainOptions: Object.freeze(fileName),
      arr: [] // 随附附件
    }
  },
  // 使用其他组件
  components: {
    Header,
    Ok,
    No,
    [Notify.Component.name]: Notify.Component,
    ImagePreview
  },
  methods: {
    handleCancel() {
      this.modalName = 'No'
    },
    // 审批同意
    handleOk() {
      if(this.transportObj.transportType !== '专车运输' && this.transportObj.state === 1) {
        this.modalName = 'Ok'
        return
      }
      let vehicleApprovalReq = {
        id: this.transportObj.id,
        flag: 1
      }
      const obj = {
        vehicleApprovalReq,
        inputApplyCarReq: this.inputApplyCarReq(this.transportObj)
      }
      // 20000以上 或者 不是专车
      if(this.isManager || this.transportObj.transportType !== '专车运输') {
        $approval
            .applyOk(obj)
            .then(res => {
              if(res.status !== 200) return this.$msg.fail(res.message || res.msg ||'出错了')
              Notify({ type: 'success', message: res.msg || res.message || '同意成功' })
              setTimeout(() => {
                this.$router.go(-1)
              }, 300)
            })
            .catch(err => this.$msg.fail(err.message || err.msg ||'出错了'))
      }
      else {
        if (this.transportObj['estimated_Freight'] > 20000) {
          this.btnLoading = false
          return alert('单位账号只能审批20000以下的数据')
        }
        $approval
            .applyDown(obj)
            .then(res => {
              if(res.status !== 200) return this.$msg.fail(res.message || res.msg ||'出错了')
              Notify({ type: 'success', message: res.msg || res.message || '同意成功' })
              setTimeout(() => {
                this.$router.go(-1)
              }, 300)
            })
            .catch(err => this.$msg.fail(err.message || err.msg ||'出错了'))
      }
    },
    handleClose() {
      this.modalName = ''
    },
    getState() {
      let state = ''
      approvalState[0].forEach(item => {
        if(item.id === this.transportObj.state) state = item.name
      })
      return state
    },
    // 文件预览下载
    handleDown(item) {
      const obj = { fileId: item.id, fileType: item.fileType }
      $approval
       .loadFile(obj)
       .then(res => {
         let _this = this
         if (res.type == 'application/json') {
            const reader = new FileReader()
            reader.onload = function() {
              const { msg } = JSON.parse(reader.result) //此处的msg就是后端返回的msg内容
              _this.$msg.fail(msg)
            }
            reader.readAsText(res)
          }
          else {
            this.previewImages = []
            // var code = 'data:image/jpeg;base64,'+ transformArrayBufferToBase64(res)
           this.url = 'data:application/pdf;base64,'+this.transformArrayBufferToBase64(res)
           console.log(this.url)
            // this.previewImages.push(code)
            // this.index = this.previewImages.length - 1
            // this.isShowPreview = true
          }
       })
       .catch(err => this.$msg.fail(res.msg))
    },
    // 解图片base64
    transformArrayBufferToBase64(buffer) {
      var binary = ''
      var bytes = new Uint8Array(buffer)
      for (var len = bytes.byteLength, i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i])
      }
      return window.btoa(binary)
    },
    // 撤销审批
    handleDelete() {
      $approval
        .delete({id: this.transportObj.id})
        .then(res => {
          if(res.status !== 200) return this.$msg.fail(res.message || res.msg || '出错了')
          Notify(res.msg || res.message || '网络错误,清稍后再试')
          setTimeout(() => {
              this.$router.go(-1)
            }, 300)
        })
        .catch(err => this.$msg.fail(err.message || err.msg ||'出错了'))
    },
    // 分拨
    handleisDistribution() {
      this.isDistribution = 1
      this.modalName = 'Ok'
    },
    // 上传回后端数据验证
    inputApplyCarReq(applyObj) {
      const obj =  {
        aog: applyObj.aog,
        applicationUnit: applyObj.applicationUnit,
        startStation: applyObj.startStation,
        targetStation: applyObj.targetStation,
        deliveryUnit: applyObj.deliveryUnit,
        deliveryPeople: applyObj.deliveryPeople,
        deliveryPhone: applyObj.deliveryPhone,
        receiveUnit: applyObj.receiveUnit,
        receivePeople: applyObj.receivePeople,
        receivePhone: applyObj.receivePhone,
        spare_phone: applyObj.spare_phone,
        innerGoodsInfoEntityList: applyObj.innerGoodsInfoEntityList,
        id: applyObj.id,
        sparePhone: applyObj.sparePhone
      }
      obj['estimated_Freight'] = applyObj.estimatedFreight
      return obj
    },
    // 转换类型
    handleChange(id) {
      $approval
        .changeDanger({id})
        .then(res => {
          if (res.status !== 200) return this.$msg.fail(res.message || res.msg || '出错了')
          Notify({ type: 'success', message: res.msg || res.message || '同意成功' })
          setTimeout(() => {
            this.$router.go(-1)
          }, 300)
        })
        .catch(err => this.$msg.fail(err.message || err.msg || '出错了'))
    }
  },
  created() {
    this.text = this.$route.query.text
    let indexOf = this.$route.query.type
    if(indexOf === '是') {
      this.show = true
    } else {
      this.show = false
    }
    this.transportObj = JSON.parse(sessionStorage.getItem('transportObj'))
    if (this.transportObj.documentsAttached) {
      this.arr = this.transportObj.documentsAttached.split(',')
    }
    if(this.transportObj.state === 1 || this.transportObj.state === 2)
      this.transportObj.transportType !== '专车运输' ? this.isShow = true : this.isShow = false
  },
  async mounted() {
    // const isManager = localStorage.getItem('isManager')
    // if (isManager !== null) {
    //   return this.isManager = isManager
    // }
    if (this.transportObj.transportType === '专车运输') {
      const result = await $approval.getInfo()
      const arr = result
          .filter(item => item.name === '手持国内运输')[0]
          .children
          .filter(item => item.name === '用车审批')[0]
          .children
      // let flag = false
      arr.forEach(item => {
        if (item.name === '审批所有数据') {
          this.isManager = true
          // flag = true
        }
      })
      // localStorage.setItem('isManager', flag)
    }
  }
}
</script>

<style scoped>
.detail-content {
  position: relative;
  top: 19.333vw;
  left: 0;
  padding: 0 10px;
  height: calc(100vh - 130px);
  overflow-y: scroll;
}
.phone {
  display: flex;
}
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  display: flex;
  justify-content: space-evenly;
}
.el-button {
  flex: 1;
}
/deep/.el-collapse {
  border-top: 0;
}
/deep/.el-collapse-item__header {
  font-size: 5vw !important;
  font-weight: bold;
}
/deep/.el-collapse-item__content {
  font-size: 3.889vw !important;
}
/deep/.el-collapse-item__content {
  padding-bottom: 0;
}
/deep/.el-form-item {
  margin-bottom: 0 !important;
}
/deep/.el-form-item__label {
  padding-bottom: 0 !important;
}
/deep/.el-form-item__error {
  padding-top: 0 !important;
}
/* 货物信息 */
.box {
  padding: 0 2.778vw;
  border: 1px solid #797979;
  border-radius: 5px;
}
.box-content {
  padding: 2.778vw 0;
  border-bottom: 0.278vw dashed #797979;
}
.box-content:last-child {
  border-bottom: 0;
}
.box-content-text {
  display: flex;
}
.box-content-text span {
  flex: 1;
}
/deep/.el-card__header {
  padding: 5px;
}
/deep/.el-card__body {
  padding: 5px;
}
.flexText {
  display: flex;
}
.flexText span:last-child {
  flex: 1;
}
.weight {
  font-weight: 600;
}
</style>
